/**   
 * @Title: MainActivity.java 
 * @Package: com.rename.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-11 下午2:05:45 
 * @version  
 */

package com.rename.icode.activity;

import android.R.bool;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.rename.icode.R;
import com.rename.icode.activity.settings.SettingsActivity;
import com.rename.icode.comm.Constants;
import com.rename.icode.dbg.LogcatHelper;
import com.rename.icode.manager.AppConfigManager;
import com.rename.icode.manager.UserManager;
import com.rename.icode.model.CodeFile;
import com.rename.icode.model.ICompiler;
import com.rename.icode.model.NativeCompiler;
import com.rename.icode.model.OnlineCompiler;
import com.rename.icode.task.LoginTask;
import com.rename.icode.utils.CommandUtil;
import com.rename.icode.utils.FileUtil;
import com.rename.icode.utils.HttpURLTools;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.utils.StringUtil;
import com.rename.icode.view.NonSwipeableViewPager;
import com.rename.icode.view.PopMenu;
import com.rename.icode.view.PopMenuOnclick;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description MainActivity
 * @author WangXinMing
 * @date 2015-2-11 下午2:05:45
 * @version V1.0
 */

public class MainActivity extends ActivityFragmentSupport implements
		OnClickListener {

	private final static String TAG = "MainActivity";
	private Context context;
	private Dialog mLanDialog;// 选择代码语言对话框
	
	private ICompiler mICompiler; // 编译器

	// 界面
	public static final int SPLASH = 0;
	public static final int MAIN = 1;
	public static final int CODE = 2;

	// 主界面
	private LinearLayout mMainActivityLayout;
	private RelativeLayout mTabLayout;
	private NonSwipeableViewPager mLayout;
	private TabsAdapter mTabsAdapter;
	private View mTabLocal;
	private View mTabServer;
	private View mTabSynchronous;
	private TextView mTabLocalTxt;
	private TextView mTabServerTxt;
	private TextView mTabSyncTxt;
	private TextView topSelectBar;

	// 菜单
	private ImageButton mPopMenuBtn;
	private PopMenu popMenu;

	// 代码编辑
	private LinearLayout mEditlLayout;
	private WebView mCodeView;
	private GridView mSymbolView;
	private HorizontalScrollView mHorizontalScrollView;
	private String mCurrentCode = null;// 存放webview中写好的代码
	private String mCurrentShowCode = null; // 存放用于显示的代码
	private CodeFile mCurrentCodeFile = null;// 当前codeFile
	private int languageID;
	private List<HashMap<String, Object>> mSymboList;
	private Button mSaveBtn;
	private Button mRunBtn;
	private EditText mFileNameText;
	private Dialog mSaveDialog;
	private boolean isNew;// 判断文件是新建的还是打开的
	public static boolean fromServer; // 判断文件是否来自ServerFragment

	// 线程
	private Thread mReadFileThread = null;
	private Thread mRunCodeThread = null;

	// private Process mProcess = null;
	private String mResult = null;

	// 头
	private ImageView mTitleView;

	// 注册登录界面
	private LinearLayout mSplashLayout;

	/**
	 * 注册登录界面
	 */
	private Button signUpBtn = null;
	private Button loginBtn = null;
	private Button leftBtn = null;
	private Button rightBtn = null;
	private Button enterBtn = null;
	private View bottomLayout = null;
	private View errorOperLayout = null;
	private View normalOperLayout = null;
	private View directEnterLayout = null;
	private ImageView loginImg = null;
	private ImageView bottomBackgroundImg = null;
	private TextView errTxt = null;

	private int lastIndex = -1;

	private static final int PAGE_FINISHED = 0;// webview页面刷新完成
	private static final int CODE_READED = 1;// 打开文件，读取文件代码完成
	private static final int SHOW_RUN_RESULT = 2;// 代码运行结束T
	private static final int NOTIFY_LOCAL_REFRESH = 3; // 通知LocalFragment文件列表刷新
	private static final int NOTIFY_SERVER_REFRESH = 4; // on告知ServerFragment文件列表刷新
	private static final int GUEST_ENTER = 5; // guest进入
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PAGE_FINISHED:
				LogUtil.i("wxm", "PAGE_FINISHED==>" + mCurrentCode);
				if (!isNew) {
//					inputCode(mCurrentCode);
					inputCode(mCurrentShowCode);
				}
				break;
			case CODE_READED:
//				Toast.makeText(context, "文件内容mCurrentCode：" + mCurrentCode, 1).show();
//				Toast.makeText(context, "文件内容mSaveCode：" + mCurrentShowCode, 1).show();
				LogUtil.i("wxm", "CODE_READED==>" + mCurrentCode);
//				inputCode(mCurrentCode);
				inputCode(mCurrentShowCode);
				break;
			case SHOW_RUN_RESULT:
				hideProgress();// 隐藏等待进度条
				// 跳转到结果显示页面
				Intent intent = new Intent();
				intent.setClass(context, ResultActivity.class);
				if (null == mResult) {
					mResult = "您的代码中存在错误，请修改后再次运行。";
				}
				LogUtil.i(TAG, "结果： " + mResult);
				intent.putExtra("result", mResult);
				// startActivity(intent);
				startActivityForResult(intent, Constants.REQCODE_EDITVIEW_OP);
				break;
			case NOTIFY_LOCAL_REFRESH:
				Intent localIntent = new Intent();
				localIntent.setAction(Constants.LOCAL_REFRESH);
				context.sendBroadcast(localIntent);
				LogUtil.i(TAG, "LOCAL_REFRESH广播发送完毕...");
				break;
			case NOTIFY_SERVER_REFRESH:
				Intent serverIntent = new Intent();
				serverIntent.setAction(Constants.SERVER_REFRESH);
				context.sendBroadcast(serverIntent);
				LogUtil.i(TAG, "SERVER_REFRESH广播发送完毕...");
				break;
			case GUEST_ENTER:
				changeViewToShow(MAIN); // 显示主界面
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		LogUtil.i(TAG, "MainActivity onCreate");
		context = this;

		mSplashLayout = (LinearLayout) findViewById(R.id.splashup_screen);// 注册、登录的加载界面
		mMainActivityLayout = (LinearLayout) findViewById(R.id.contacter_main);// 主界面
		// 日志信息重定向到文件中
		// initLogcatHelper();
		// 自定义异常捕捉
		// CrashHandler crashHandler = CrashHandler.getInstance();
		// crashHandler.init(getApplicationContext());

		if (FileUtil.getSDCardRootDirectory() == null) {// 检查SDCard是否正确挂载
			showToast(getApplicationContext().getString(R.string.sdcard_not_mount), 0);
			return;
		}

		init();

		initSplashlayout();
	}

	@Override
	protected void onResume() {
		super.onResume();
		LogUtil.i(TAG, "onResume()");
		if (checkInternet()) {
			LogUtil.i(TAG, "network check pass start login icode account");
			normalOperation();
		} else {
			LogUtil.i(TAG, "network check don't pass,");
			directEnterLayout.setVisibility(View.VISIBLE);
			enterBtn.setVisibility(View.VISIBLE);
		}
		initCompiler();
	}

	private void initLogcatHelper() {
		LogcatHelper.getInstance(context).stop();
		LogcatHelper.getInstance(context).start();
	}

	private void init() {
		getICodeApplication().addActivity(this);
		isNew = false;
		fromServer = false;
		mCurrentCodeFile = new CodeFile();
		mTabLayout = (RelativeLayout) findViewById(R.id.tab_layout);
		mTabLocal = findViewById(R.id.tab_local_layout);
		mTabServer = findViewById(R.id.tab_server_layout);
		mTabSynchronous = findViewById(R.id.tab_synchronous_layout);
		mTabLocalTxt = (TextView) findViewById(R.id.tab_local);
		mTabServerTxt = (TextView) findViewById(R.id.tab_server);
		mTabSyncTxt = (TextView) findViewById(R.id.tab_synchronous);

		topSelectBar = (TextView) findViewById(R.id.top_bar_select);

		OnClickListener onViewClick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (v.getId() == R.id.title_popmenu) { // 点击popmenu按钮
					popMenu.showAsDropDown(v);
				}
			}
		};
		mPopMenuBtn = (ImageButton) findViewById(R.id.title_popmenu);
		mPopMenuBtn.setOnClickListener(onViewClick);

		popMenu = new PopMenu(context);
		// 添加popmenu菜单子项
		popMenu.addItem("新建");
		popMenu.addItem("打开");
		popMenu.addItem("偏好");
		popMenu.addItem("设置");
		popMenu.setOnItemClickListener(new PopMenuOnclick() {

			@SuppressLint("SetJavaScriptEnabled")
			@Override
			public void onClick(int position) {
				switch (position) {
				case 0:// new
					mLanDialog.show();// 选择语言
					isNew = true;
					fromServer = false;
					break;
				case 1:// open
					Intent sDCardIntent = new Intent();
					sDCardIntent.setClass(context, SDCardFileExplorerActivity.class);
					startActivityForResult(sDCardIntent, Constants.REQCODE_EDITVIEW_OP);
					break;
				case 2:// preferences
					break;
				case 3:// settings
					Intent settingsIntent = new Intent();
					settingsIntent.setClass(context, SettingsActivity.class);
					startActivity(settingsIntent);
					break;
				default:
					break;
				}

				popMenu.dismiss();
			}
		});

		mEditlLayout = (LinearLayout) findViewById(R.id.edit_layout);
		mCodeView = (WebView) findViewById(R.id.webview_code);
		mSymbolView = (GridView) findViewById(R.id.gridview_symbol);
		mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
		mHorizontalScrollView.setHorizontalScrollBarEnabled(false);// 隐藏滑动条
		mSymboList = new ArrayList<HashMap<String, Object>>();
		int num = 10;
		for (int i = 0; i < num; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("symbol", "(");
			mSymboList.add(map);
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(context, mSymboList,
				R.layout.symbol_item, new String[] { "symbol" },
				new int[] { R.id.textview_symbol });
		mSymbolView.setAdapter(simpleAdapter);
		mSymbolView.setNumColumns(num);
		int symbolItemWidth = 50;
		int gap = 0;
		int symbolViewWidth = (symbolItemWidth + gap) * mSymbolView.getCount();
		LayoutParams params = new LayoutParams(symbolViewWidth,
				LayoutParams.WRAP_CONTENT);
		mSymbolView.setLayoutParams(params);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		mSymbolView.setColumnWidth(dm.widthPixels / num);
		mSymbolView.setStretchMode(GridView.NO_STRETCH);
		mSymbolView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String value = mSymboList.get(position).get("symbol")
						.toString();
				showToast("当前选择的符号是 " + value, 0);
				// TODO:输入到webview的页面中
				inputCommonSymbol(value);
			}
		});

		mTitleView = (ImageView) findViewById(R.id.title_img);
		mTitleView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				changeViewToShow(MainActivity.MAIN);// 回到主界面
			}
		});

		mLanDialog = new AlertDialog.Builder(context)
				.setTitle("选择语言")
				.setIcon(R.drawable.ic_launcher)
				.setSingleChoiceItems(Constants.TYPES, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								languageID = which;
							}

						})
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						LogUtil.i(TAG, "选择语言，确定");
						LogUtil.i(TAG, "languageid is " + languageID);

						mCurrentCode = null; // 新建置空mCurrentCode
						mCurrentCodeFile = new CodeFile(); // 新建置空mCurrentCodeFile
						// 新建的文件设置类型
						if (languageID == Constants.CODE_C) {
							mCurrentCodeFile.setType(Constants.TYPE_C);
						} else if (languageID == Constants.CODE_CPP) {
							mCurrentCodeFile.setType(Constants.TYPE_CPP);
						} else if (languageID == Constants.CODE_JAVA) {
							mCurrentCodeFile.setType(Constants.TYPE_JAVA);
						}
						LogUtil.i(TAG, "mCurrentCodeFile type is "
								+ mCurrentCodeFile);

						mCurrentCodeFile.setPath(Constants.CODE_LOCAL_DIR);// 新建的文件都保存到本地代码文件根目录

						changeViewToShow(MainActivity.CODE);// 新建代码编辑页
						// TODO:根据用户选择不同的语言webview绑定不同的html文件
						showCodeViewByLanguage(false, mCurrentCodeFile);
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						LogUtil.i(TAG, "选择语言，取消");
					}
				}).create();

		mSaveBtn = (Button) findViewById(R.id.save_btn);
		mSaveBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 如果是新建的文件则跳出对话框填写文件名，如果不填写，文件将不保存
				if (isNew) {// 新建的
					mSaveDialog.show();
				} else {// 打开的
					// saveCodeToFile(mCurrentCLID, mCurrentFileName);
					saveCodeToFile(mCurrentCodeFile);
					// TODO 如果是保存服务器文件，则需要增加上传文件这一步
					if (fromServer) {

					}
				}
			}
		});
		mFileNameText = new EditText(context);
		mSaveDialog = new AlertDialog.Builder(context)
				.setTitle("保存")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setView(mFileNameText)
				.setPositiveButton("确认", new DialogInterface.OnClickListener() {

					@SuppressWarnings("unused")
					@Override
					public void onClick(DialogInterface dialog, int which) {
						LogUtil.i(TAG, "文件名，确定");
						// 保存文件
//						Toast.makeText(context, "save", Toast.LENGTH_SHORT)
//								.show();
						// mCurrentFileName = mFileNameText.getText().toString()
						// .trim();// 新建文件，确定当前文件名
						mCurrentCodeFile.setName(mFileNameText.getText()
								.toString().trim());
						Field field = null;
						try {// 通过反射机制获得私有变量mShowing(表示对话框是否显示)
							field = dialog.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							// 将mShowing设置为false，表示对话框已经关闭
							field.set(dialog, false);
						} catch (Exception e) {
							e.printStackTrace();
						}
						// TODO 判断SD卡中是否已存在相同名称的文件
						if (existSameNameFile(mCurrentCodeFile)) {// 存在
							mFileNameText.setText("");
							if (null != field) {
								try {
									field.set(dialog, false);// 使对话框不可以关闭
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						} else {// 不存在
							// saveCodeToFile(mCurrentCLID, mCurrentFileName);
							saveCodeToFile(mCurrentCodeFile);
							isNew = false;// 保存完之后，文件属于打开的，不属于新建的，则不需要给文件重命名
							// mCurrentFileName = "";// 保存完后，当前文件名置为空字符串
							mCurrentCodeFile.setName("");
							if (null != field) {
								try {
									field.set(dialog, true);// 使对话框可以关闭
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						LogUtil.i(TAG, "文件名，取消");
						// 取消保存
//						Toast.makeText(context, "save canel",
//								Toast.LENGTH_SHORT).show();
						try {// 通过反射机制获得私有变量mShowing(表示对话框是否显示)
							Field field = dialog.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							// 将mShowing设置为true，表示对话框未关闭
							field.set(dialog, true);// 使对话框可以关闭
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).create();
		mRunBtn = (Button) findViewById(R.id.run_btn);
		mRunBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 运行代码
//				Toast.makeText(context, "run", Toast.LENGTH_SHORT).show();
				// TODO:运行前先判断文件是否保存，如果未保存先保存
				// saveCodeToFile(mCurrentCLID, mCurrentFileName);
				saveCodeToFile(mCurrentCodeFile);
				pg.setMessage("正在运行代码...");
				pg.show();
				mRunCodeThread = new Thread() {

					@Override
					public void run() {
						compile(mCurrentCodeFile);
//						mResult = (String) mICompiler.compile(mCurrentCodeFile);
						LogUtil.i(TAG, "准备进入结果界面...");
						mHandler.sendEmptyMessage(SHOW_RUN_RESULT);
					}

				};
				mRunCodeThread.start();

			}
		});

		addFragmentTab();
	}

	private void initSplashlayout() {
		LogUtil.i(TAG, "initSplashlayout");
		bottomLayout = findViewById(R.id.bottom_navi_layout);
		errorOperLayout = findViewById(R.id.error_oper_layout);
		normalOperLayout = findViewById(R.id.normal_oper_layout);
		directEnterLayout = findViewById(R.id.direct_enter_layout);
		loginImg = (ImageView) findViewById(R.id.loading_img);
		bottomBackgroundImg = (ImageView) findViewById(R.id.bottom_background_img);

		errTxt = (TextView) findViewById(R.id.error_msg_txt);

		leftBtn = (Button) findViewById(R.id.left_btn);
		rightBtn = (Button) findViewById(R.id.right_btn);
		
		enterBtn = (Button) findViewById(R.id.enter_btn);
		
		enterBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 初始化登录用户为guest
				AppConfigManager.getInstance().setPassword(Constants.GUEST);
				AppConfigManager.getInstance().setUsername(Constants.GUEST);
				// 初始化本地文件
				new Thread(){

					@Override
					public void run() {
						UserManager.getInstance().init();
						mHandler.sendEmptyMessage(GUEST_ENTER);
					}
					
				}.start();
			}
		});

		signUpBtn = (Button) findViewById(R.id.signup_btn);
		loginBtn = (Button) findViewById(R.id.login_btn);

		signUpBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LogUtil.i(TAG, "注册");
				Intent intent = new Intent();
				intent.setClass(context, SignUpActivity.class);
				startActivityForResult(intent, Constants.REQCODE_LOGIN_OP);
			}
		});

		loginBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LogUtil.i(TAG, "登录");
				Intent intent = new Intent();
				intent.setClass(context, LoginActivity.class);
				startActivityForResult(intent, Constants.REQCODE_LOGIN_OP);
			}
		});
	}

	public void normalOperation() {
		if (View.GONE == mEditlLayout.getVisibility()) { // 如果编辑界面隐藏了，则显示主界面
			if(!Constants.GUEST.equals(AppConfigManager.getInstance().getUsername())){ // 如果不是游客，保存用户信息
				AppConfigManager.getInstance().saveLoginConfig();
			}
			bottomBackgroundImg.setVisibility(View.GONE);
			errorOperLayout.setVisibility(View.GONE);
			normalOperLayout.setVisibility(View.VISIBLE);
			bottomLayout.setVisibility(View.VISIBLE);
			directEnterLayout.setVisibility(View.VISIBLE);

			// auto login if already signup
			String userName = AppConfigManager.getInstance().getUsername();
			String password = AppConfigManager.getInstance().getPassword();
			LogUtil.i(TAG, "username is " + userName);
			LogUtil.i(TAG, "pwd is " + password);

			boolean userNameIsNull = (userName == null || userName.length() == 0);
			boolean passwordIsNull = (password == null || password.length() == 0);
			if (!userNameIsNull && !passwordIsNull) { // 自动登录
				if(Constants.GUEST.equals(AppConfigManager.getInstance().getUsername())){
					return;
				}
				LogUtil.i(TAG, "start login automatically,userName is :"
						+ userName);
				loginImg.setVisibility(View.VISIBLE);
				LoginTask loginTask = new LoginTask(this,
						(AnimationDrawable) loginImg.getBackground());
				loginTask.execute();
			} else if (!userNameIsNull && passwordIsNull) { // 密码为空，则跳转到登录界面重新登录
				LogUtil.i(TAG, "start login manually,userName is :" + userName);

				Intent intent = new Intent();
				intent.setClass(context, LoginActivity.class);
				startActivityForResult(intent, Constants.REQCODE_LOGIN_OP);

			} else { // 没有用户，到splash界面
				LogUtil.i(TAG, "start splash, no user");
				signUpBtn.setVisibility(View.VISIBLE);
				loginBtn.setVisibility(View.VISIBLE);
				enterBtn.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// int requestCode, int resultCode, Intent data
		// TODO:
		if (arg1 == RESULT_OK) {
			switch (arg0) {
			case Constants.REQCODE_LOGIN_OP:
				LogUtil.i(TAG, "登录成功");
				changeViewToShow(MainActivity.MAIN); // 登录成功，进入主界面
				break;
			case Constants.REQCODE_EDITVIEW_OP:
				changeViewToShow(MainActivity.CODE); // 显示编辑界面
				if(arg2 != null){ // 打开SDCard中其他地方的文件回传
					CodeFile codeFile = arg2.getParcelableExtra(SDCardFileExplorerActivity.SD_FILE_KEY);
					LogUtil.i(TAG, "codefile is null is " + (codeFile == null));
					if(codeFile != null){
						showCodeViewByLanguage(true, codeFile); 
					}
				}
				break;
			default:
				break;
			}
		}
	}

	private void changeViewToShow(int witch) {
		switch (witch) {
		case 0:// 登录界面
			mSplashLayout.setVisibility(View.VISIBLE);
			mMainActivityLayout.setVisibility(View.GONE);
			mEditlLayout.setVisibility(View.GONE);
			break;
		case 1:// 主界面
			mSplashLayout.setVisibility(View.GONE);
			mMainActivityLayout.setVisibility(View.VISIBLE);
			mTabLayout.setVisibility(View.VISIBLE);// 3个tab键
			mEditlLayout.setVisibility(View.GONE);
			break;
		case 2:// 编辑界面
			mSplashLayout.setVisibility(View.GONE);
			mMainActivityLayout.setVisibility(View.VISIBLE);
			mTabLayout.setVisibility(View.GONE);
			mEditlLayout.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}

	}

	private void addFragmentTab() {
		ArrayList<Fragment> frglist = new ArrayList<Fragment>();
		LocalFragment mLocalFragment = LocalFragment.getLocalFragmentIntance();
		frglist.add(mLocalFragment);
		ServerFragment mServerFragment = ServerFragment
				.getServerFragmentIntance();
		frglist.add(mServerFragment);
		SynchronousFragment mCalllogsFragment = SynchronousFragment
				.getSynchronousFragmentIntance();
		frglist.add(mCalllogsFragment);

		mLayout = (NonSwipeableViewPager) findViewById(R.id.scrolllayout);
		mLayout.setOffscreenPageLimit(2);
		mTabsAdapter = new TabsAdapter(this.getSupportFragmentManager(),
				frglist);
		mLayout.setAdapter(mTabsAdapter);
		mLayout.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				Log.i(TAG, "onPageSelected " + arg0);
				setCurrentFragement(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		mLayout.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP
						&& lastIndex == 1) {
					Log.i(TAG, "MotionEvent.ACTION_UP");
				}
				return false;
			}
		});
		setCurrentFragement(0);
	}

	private class TabsAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> mTabs = new ArrayList<Fragment>();

		public TabsAdapter(FragmentManager fm, ArrayList<Fragment> mTabs) {
			super(fm);
			this.mTabs = mTabs;
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}

		@Override
		public Fragment getItem(int position) {
			return mTabs.get(position);
		}

	}

	private void setCurrentFragement(int position) {
		mLayout.setCurrentItem(position);
		if (lastIndex != -1) {
			doChange(lastIndex, position);
		}
		lastIndex = position;
	}

	public void doChange(int lastIndex, int currentIndex) {
		if (lastIndex != currentIndex) {
			TranslateAnimation animation = null;
			int delta = ((LinearLayout) mTabLocal).getWidth();

			switch (currentIndex) {
			case 0:
				if (lastIndex == 1) {
					animation = new TranslateAnimation(delta, 0, 0, 0);
				} else if (lastIndex == 2) {
					animation = new TranslateAnimation(delta * 2, 0, 0, 0);
				}
				mTabLocalTxt.setTextColor(getResources().getColor(
						R.color.button_deep_green));
				mTabServerTxt.setTextColor(getResources().getColor(
						R.color.darkgray));
				mTabSyncTxt.setTextColor(getResources().getColor(
						R.color.darkgray));

				break;
			case 1:
				if (lastIndex == 0) {
					animation = new TranslateAnimation(0, delta, 0, 0);
				} else if (lastIndex == 2) {
					animation = new TranslateAnimation(delta * 2, delta, 0, 0);
				}
				mTabLocalTxt.setTextColor(getResources().getColor(
						R.color.darkgray));
				mTabServerTxt.setTextColor(getResources().getColor(
						R.color.button_deep_green));
				mTabSyncTxt.setTextColor(getResources().getColor(
						R.color.darkgray));
				break;
			case 2:
				if (lastIndex == 1) {
					animation = new TranslateAnimation(delta, delta * 2, 0, 0);
				} else if (lastIndex == 0) {
					animation = new TranslateAnimation(0, delta * 2, 0, 0);
				}
				mTabLocalTxt.setTextColor(getResources().getColor(
						R.color.darkgray));
				mTabServerTxt.setTextColor(getResources().getColor(
						R.color.darkgray));
				mTabSyncTxt.setTextColor(getResources().getColor(
						R.color.button_deep_green));
				break;
			}
			animation.setDuration(300);
			animation.setFillAfter(true);
			topSelectBar.startAnimation(animation);
		}
	}

	/**
	 * Description
	 * 
	 * @param v
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */

	@Override
	public void onClick(View v) {
		if (v == mTabLocal) {
			setCurrentFragement(0);
		} else if (v == mTabServer) {
			setCurrentFragement(1);
		} else if (v == mTabSynchronous) {
			setCurrentFragement(2);
		}
	}

	/**
	 * 
	 * @Description 打开代码编辑界面
	 * @author Administrator
	 * @param isOpen
	 *            为true则打开fileName文件，为false则新建一个空的代码编辑界面
	 * @param fileName
	 *            打开的文件，只有isOpen为true时才有意义
	 */
	@SuppressLint("SetJavaScriptEnabled")
	public void showCodeViewByLanguage(boolean isOpen, final CodeFile codeFile) {

		if (null != codeFile) {
			// 读取文件
			if (isOpen) {
				mCurrentCodeFile = codeFile;
				LogUtil.i("wxm", "打开文件");
				if (FileUtil.isFileExist(codeFile.getPath())) {// 文件存在
					mReadFileThread = new Thread() {// 读取文件内容显示在代码编辑界面

						@Override
						public void run() {
							File file = new File(codeFile.getPath());
							List<String> strings = new ArrayList<String>();
							strings = FileUtil.readFileToStrings(file);
							mCurrentCode = "";
							mCurrentShowCode = "";
							int i = 0;
//							for (String string : strings) {
//								if (i < strings.size() - 1) {
//									mCurrentCode += string + "\\n";// 由于与js交互时，js无法识别参数中的换行，只能将'\n'进行转义"\\n"
//								} else {
//									mCurrentCode += string;
//								}
//								mCurrentShowCode += string + "\n";
//								i++;
//							}
							for (String string : strings) {
								if (i < strings.size() - 1) {
									mCurrentShowCode += string + "\\n";// 由于与js交互时，js无法识别参数中的换行，只能将'\n'进行转义"\\n"
								} else {
									mCurrentShowCode += string;
								}
								mCurrentCode += string + "\n";
								i++;
							}
							LogUtil.i(TAG, "文件内容mCurrentCode：" + mCurrentCode);
							LogUtil.i(TAG, "文件内容mCurrentShowCode：" + mCurrentShowCode);
							mHandler.sendEmptyMessage(CODE_READED);
						}

					};
					mReadFileThread.start();
				} else {
					LogUtil.i("wxm", "文件不存在：" + codeFile.getPath());
//					Toast.makeText(context, "文件不存在，为您创建一个空文件",
//							Toast.LENGTH_SHORT).show();
					showToast("文件不存在，为您创建一个空文件", Toast.LENGTH_SHORT);
				}
			}

			// 创建webview
			String url = Constants.HTML_ROOT_DIR;

			String type = codeFile.getType();
			LogUtil.i(TAG, "type is " + type);
			if (Constants.TYPE_C.equals(type)) {
				url += Constants.TYPE_C;
			} else if (Constants.TYPE_CPP.equals(type)) {
				url += Constants.TYPE_CPP;
			} else if (Constants.TYPE_JAVA.equals(type)) {
				url += Constants.TYPE_JAVA;
			} else { // 如果是其他无法编译的文件
				showToast("此类文件无法编译");
				return;
			}

			url += "/" + Constants.CODE_HTML;
			mCodeView.loadUrl(url);
			mCodeView.addJavascriptInterface(new CodeHandler(), "handler");
			mCodeView.setWebViewClient(new WebViewClient() {

				@Override
				public void onPageFinished(WebView view, String url) {
//					Toast.makeText(context, "网页加载完成", 0).show();
					mHandler.sendEmptyMessage(PAGE_FINISHED);// 发送消息，页面加载完成
					super.onPageFinished(view, url);
				}

			});
			mCodeView.getSettings().setJavaScriptEnabled(true);
		}

	}

	/**
	 * 
	 * @Description 用于js调用Java的方法
	 * @author Administrator
	 * @date 2015-3-16 上午11:32:35
	 * @version V1.0
	 */
	class CodeHandler {
		public void save(String data) {
			mCurrentCode = data;
//			mSaveCode = data;
			LogUtil.i(TAG, "页面上的代码：" + mCurrentCode);
//			Toast.makeText(context, "页面上的代码111：" + mCurrentCode, 1).show();
			LogUtil.i("ll", "页面上的代码111：" + mCurrentCode);
		}
	}

	/**
	 * 
	 * @Description 把代码保存到指定路径文件中，如果文件不存在则创建新文件，保存到本地文件
	 * @author Administrator
	 * @param codeFile
	 */
	private void saveCodeToFile(CodeFile codeFile) {
		if (null == codeFile.getName()) {
			LogUtil.i(TAG, "保存的文件名为空，保存失败");
			return;
		}
		webViewCallJS(mCodeView, Constants.JS_GET_CODE);// 获取页面代码，存于mCurrentCode
//		Toast.makeText(context, "页面上的代码222：" + mCurrentCode, 1).show();
		LogUtil.i("ll", "页面上的代码222：" + mCurrentCode);

		if (isNew) { // 如果文件是新建的，则它的路径需要重新设置正确
			codeFile.setPath(codeFile.getPath() + codeFile.getName());
		}
		File file = null;
		String filePath = codeFile.getPath();
		file = new File(filePath);
		if (!file.exists()) {
			LogUtil.i(TAG, "文件不存在，创建文件");
			FileUtil.createNewFile(file);
		}
		LogUtil.i(TAG, "代码写入文件");
		LogUtil.i(TAG, "mCurrentCode is null " + (null == mCurrentCode));
		if (null != mCurrentCode) {
			LogUtil.i(TAG, "mCurrentCode " + mCurrentCode);
			boolean finished = FileUtil.write(file, mCurrentCode);
			LogUtil.i(TAG, "文件写入完成？" + finished);
			if(finished){
				showToast("文件保存完成", 0);
			}
		}

		new Thread() {

			@Override
			public void run() {
				// 通知刷新本地文件列表
				UserManager.getInstance().refreshLocalData();
				mHandler.sendEmptyMessage(NOTIFY_LOCAL_REFRESH);
			}

		}.start();
	}

	/**
	 * 
	 * @Description 判断是否存在同名的文件
	 * @author Administrator
	 * @param languageID
	 * @param fileName
	 * @return
	 */
	private boolean existSameNameFile(CodeFile codeFile) {
		String fileName = codeFile.getName();
		String filePath = codeFile.getPath();
		String fileDir = filePath.substring(0,
				filePath.length() - fileName.length());
		File[] files = FileUtil.getFiles(fileDir);
		if (null != files) {
			for (File file : files) {
				if (file.getName().equals(fileName)) {
					// 存在该名称的文件
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 
	 * @Description 初始化编译器
	 * @author Administrator
	 */
	private void initCompiler(){
		if(mICompiler == null){
			if(Constants.GUEST.equals(AppConfigManager.getInstance().getUsername())){ // 如果是guest账户
//				mICompiler = new NativeCompiler();
				mICompiler = NativeCompiler.getInstance();
			}else { // 如果是正常登录
//				mICompiler = new OnlineCompiler();
				mICompiler = OnlineCompiler.getInstance();
			}
		}
	}

	/**
	 * 
	 * @Description 编译运行代码
	 * @author Administrator
	 * @param codeFile
	 */
	private void compile(CodeFile codeFile) {
		if(Constants.GUEST.equals(AppConfigManager.getInstance().getUsername())){ // 如果是guest账户
			mResult = NativeCompiler.getInstance().compile(codeFile);
//			if (null != results) {//
//				mResult = "";
//				for (String result : results) {
//					mResult += result + "\n";
//				}
//			} else {
//				mResult = null;
//			}
		}else { // 正常登录
			String sdPath = codeFile.getPath().replaceAll(
					codeFile.getName(), "");
			String username = UserManager.getInstance().getUser().getName();

			LogUtil.i(TAG, "sdPath is " + sdPath);

			if (Constants.CODE_LOCAL_DIR.equals(sdPath)) {
				LogUtil.i(TAG, "本地");
				/*
				 * 如果是本地文件，首先上传文件，再发送文件名+用户名请求文件上传到服务器，得到代码编译后的结果
				 */
				mResult = HttpURLTools.postFile(Constants.UPLOAD_URL,
						codeFile.getPath(), username);
				if (StringUtil.empty(mResult)
						|| Constants.UPLOAD_FAIL.equals(mResult)) {
					LogUtil.i(TAG, "文件上传失败");
					return;
				} else {
					LogUtil.i(TAG, "上传文件返回结果：" + mResult);
				}
				UserManager.getInstance().refreshSeverData(); // 文件上传完成，刷新服务器文件列表
				mHandler.sendEmptyMessage(NOTIFY_SERVER_REFRESH); // ServerFragment界面刷新通知
			} else if (Constants.CODE_SERVER_DIR.equals(sdPath)) { // 如果是服务器文件，文件名+用户名请求
				LogUtil.i(TAG, "服务器");
			} else { // 其他路径
				LogUtil.i(TAG, "编译其他路径文件");
			}

			// 发送文件编译请求
			Map<String, String> params = new HashMap<String, String>();
			params.put("userinfo", username);
			params.put("codename", codeFile.getName());
			HttpResponse response = HttpURLTools.sendHttpPost(
					Constants.COMPILER_URL, params);

			if (null != response) {
				try {
					mResult = EntityUtils.toString(response.getEntity());
					LogUtil.i(TAG, "编译文件返回结果：" + mResult);
				} catch (ParseException | IOException e) {
					e.printStackTrace();
				}
			} else {
				mResult = null;
			}
		}
	}
	
	/**
	 * 
	 * @Description 在本地编译运行代码
	 * @author Administrator
	 * @param filePath
	 * @return
	 */
	private List<String> nativeRun(String filePath) {
		LogUtil.i(TAG, "nativeRun filePath is " + filePath);
		List<String> results = null;
		String compileCmd = "gcc " + filePath + " -o " + Constants.EXE_FILE;
		String[] commands = new String[] { Constants.CMD_EXPORT_GCCHOME,
				Constants.CMD_EXPORT_GCCPATH, Constants.CMD_EXPORT_PATH,
				Constants.CMD_GCC_ROOT, compileCmd, Constants.CMD_RUN };
		results = CommandUtil.excuteCommand(commands); // 编译
		LogUtil.i(TAG, "nativeRun results is null is " + (null == results));

		return results;
	}

	/**
	 * 
	 * @Description 向网页中输入常用字符
	 * @author Administrator
	 * @param symbol
	 */
	private void inputCommonSymbol(String symbol) {
		if (null == symbol) {
			throw new NullPointerException();
		}
		String jsString = "javascript:insertSymbol('" + symbol + "')";// 快捷输入常用字符
		webViewCallJS(mCodeView, jsString);
	}

	/**
	 * 
	 * @Description 向网页中输入一段代码
	 * @author Administrator
	 * @param code
	 */
	private void inputCode(String code) {
		if (null == code) {
			throw new NullPointerException();
		}
		LogUtil.i("wxm", "inputCode code " + code);
		String jsString = "javascript:setContent('" + code + "')";
		webViewCallJS(mCodeView, jsString);
	}

	/**
	 * 
	 * @Description webview调用js实现网页与Android交互
	 * @author Administrator
	 * @param webView
	 * @param jsString
	 */
	private void webViewCallJS(WebView webView, String jsString) {
		webView.loadUrl(jsString);
//		Toast.makeText(context, "jsString is " + jsString, 1).show();
	}

	/**
	 * 
	 * @Description 对外接口，改变页面显示
	 * @author Administrator
	 * @param witch
	 */
	public void changeLayout(int witch) {
		changeViewToShow(witch);
	}

	// 重置注册、登录按钮
	public void setLoginBtnSignBtnVisible() {
		signUpBtn.setVisibility(View.VISIBLE);
		loginBtn.setVisibility(View.VISIBLE);
	}

	public void hideLoginAnim() {
		loginImg.setVisibility(View.GONE);
	}

	/**
	 * 
	 * @Description 关闭线程
	 * @author Administrator
	 */
	private void stopThread() {
		if (null != mReadFileThread) {
			mReadFileThread = null;
		}
		if (null != mRunCodeThread) {
			mRunCodeThread = null;
		}
	}

	@Override
	protected void onDestroy() {
		LogUtil.i(TAG, "onDestroy()");
		stopThread();
		super.onDestroy();
	}

	// TODO 设置一个响应时间time，如果超过time进度框自动关闭，并提示加载或者运行失败

	/**
	 * 
	 * @Description 检测网络状态
	 * @author Administrator
	 * @return
	 */
	private boolean checkInternet() {
		LogUtil.i(TAG, "checkInternet()");
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager == null) {
			showErrorInternetView();
			return false;
		} else {
			NetworkInfo[] info = manager.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}

		showErrorInternetView();
		return false;
	}

	/**
	 * 
	 * @Description 无网络显示的界面
	 * @author Administrator
	 */
	private void showErrorInternetView() {
		errTxt.setText(getResources().getString(
				R.string.have_not_accessiable_network));
		leftBtn.setText(getResources().getString(R.string.exit));
		leftBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				icodeApplication.exit();
			}
		});

		rightBtn.setText(getResources().getString(R.string.settings));
		rightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});

		bottomBackgroundImg.setVisibility(View.VISIBLE);
		errorOperLayout.setVisibility(View.VISIBLE);
		bottomLayout.setVisibility(View.VISIBLE);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	        moveTaskToBack(true);
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
}
